package com.crm.controller;

import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.crm.model.pojo.Care;
import com.crm.model.pojo.Customer;
import com.crm.model.pojo.Dictionary;
import com.crm.services.CareServices;
import com.crm.services.ContactServices;
import com.crm.services.CustomerServices;
import com.crm.services.DictionaryServices;
import com.crm.services.UserServices;
import com.crm.util.LoginUtil;
import com.github.pagehelper.PageInfo;

@Controller
@RequestMapping("/aftersale")
public class CareController {
	@Autowired
	CareServices careServices;
	@Autowired
	UserServices userservices;
	@Autowired
	CustomerServices customerServices;
	@Autowired
	DictionaryServices dictionaryServices;
	@Autowired
	ContactServices contactServices;
	
	@GetMapping("/care")
	public ModelAndView selectallCare(Integer pageNum, Integer pageSize,Integer statueID,String search) {
		if (pageNum == null)
			pageNum = 1;
		if (pageSize == null)
			pageSize = 6;
		ModelAndView mv = new ModelAndView("/aftersale/care");
		System.out.println("客户关怀！");
		//查询分页
		List<Map<String, String>> selectPage = careServices.selectPage(pageNum, pageSize,statueID,search);
		System.out.println(selectPage);
		String jsonString = JSONObject.toJSONString(selectPage);
		//获取分页信息
		PageInfo<Map<String, String>> page = new PageInfo<Map<String, String>>(selectPage);
		System.out.println(page);
		String pageInfo = JSONObject.toJSONString(page);
		System.out.println(page);
		mv.addObject("list", jsonString);
		mv.addObject("page", page);
		mv.addObject("pageinfo", pageInfo);
		return mv;
	}
	
	/**
	 * 分页查询获取关怀（刷新表单）
	 * @param pageNum
	 * @param pageSize
	 * @param statueID
	 * @param search
	 * @return
	 */
	@PostMapping("/care")
	@ResponseBody	
	public PageInfo<Map<String, String>> findcareNew(Integer pageNum, Integer pageSize,Integer statueID,String search) {
		if (pageNum == null)
			pageNum = 1;
		if (pageSize == null)
			pageSize = 6;
		//分页查询关怀
		System.out.println("Complaint:"+pageNum+"\t"+pageSize+"\t"+statueID+"\t"+search);
		List<Map<String, String>> selectPage = careServices.selectPage(pageNum, pageSize, statueID, search);
		//获取分页信息
		PageInfo<Map<String, String>> page = new PageInfo<Map<String, String>>(selectPage);
		return page;
	}
	
	/**
	 * 查询单条
	 * @param careid
	 * @return
	 */
	@PostMapping("/careOne")
	@ResponseBody
	public JSONObject getComplaintByid(@RequestParam("c_id") Integer careid) {
		System.out.println("关怀编号："+ careid);
		//根据编号查询投诉信息
		Map<String, String> care = careServices.selectByid(careid);
		// 查询所有客户
		List<Map<String, String>> allCustomerName = customerServices.selectAllCustomer();
		System.out.println("客户名：" + allCustomerName);
		// 查询所有用户名
		List<Map<String, String>> allusername = userservices.selectUserAll();
		System.out.println("所有用户:" + allusername);
		// 查询关怀分类
		List<Dictionary> careClassify = dictionaryServices.findByDictParentid(1070);
		System.out.println("关怀分类：" + careClassify);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("careInfo", care);
		jsonObject.put("userInfo", allusername);
		jsonObject.put("customerInfo", allCustomerName);
		jsonObject.put("careClassifyInfo", careClassify);
		return jsonObject;
	}
	
	/**
	 * 新增时查询对应可选数据
	 * @return
	 */
	@PostMapping("/chooseCareOptions")
	@ResponseBody
	public JSONObject addoptions() {
		// 查询所有客户
		List<Map<String, String>> allCustomerName = customerServices.selectAllCustomer();
		System.out.println("客户名：" + allCustomerName);
		// 查询所有用户名
		List<Map<String, String>> allusername = userservices.selectUserAll();
		System.out.println("所有用户:" + allusername);
		// 查询关怀分类
		List<Dictionary> careClassify = dictionaryServices.findByDictParentid(1070);
		System.out.println("关怀分类：" + careClassify);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("userInfo", allusername);
		jsonObject.put("customerInfo", allCustomerName);
		jsonObject.put("careClassifyInfo", careClassify);
		jsonObject.put("user", LoginUtil.getUser());
		return jsonObject;
	}
	
	/**
	 * 根据联系人编号查询纪念日作为关怀主题
	 * 
	 * @param conName
	 */
	@RequestMapping("/conToMemory")
	@ResponseBody
	public JSONObject selectcusttocon(@RequestParam("conid") Integer conid) {
		Map<String, String> queryContact = contactServices.queryContact(conid);
		JSONObject jsonObject = new JSONObject();
		System.out.println("纪念日："+queryContact);
		jsonObject.put("conToMemory", queryContact);// 纪念日
		return jsonObject;
	}
	
	
	/**
	 * 逻辑删除
	 * @param complaintId
	 * @return
	 */
	@RequestMapping("/caredeleteone")
	@ResponseBody
	public int deleteone(@RequestParam("ID")Integer careid) {	
		System.out.println("删除单个:"+careid);
		careServices.deleteByStatue(careid);
		return 1;			
	}
	
	/**
	 * 编辑客户关怀
	 */
	@PostMapping("/updateCare")
	@ResponseBody
	public String updateCare(@RequestParam("ID") Integer careid,
			@RequestParam(name = "caretheme", required = false) String caretheme,
			@RequestParam(name = "custID", required = false) Integer carecust,
			@RequestParam(name = "contID", required = false) Integer careContacts,
			@RequestParam(name = "caredate", required = false) String caredate,
			@RequestParam(name = "doname", required = false) Integer carehasman,
			@RequestParam(name = "careclassity", required = false) Integer caretype,
			@RequestParam(name = "textcare", required = false) String textcare,
			@RequestParam(name = "custreturn", required = false) String custreturn,
			@RequestParam(name = "textremark", required = false) String textremark) {
		// 转换日期格式
		java.sql.Date datenew = java.sql.Date.valueOf(caredate.substring(0, 10));
		System.out.println("时间日期："+datenew);
		Care care = new Care();
		System.out.println("care编号："+careid+"客户编号："+carecust);
		// 修改
		care.setCareId(careid);;//关怀编号
		care.setCareTheme(caretheme);;//关怀主题
		Customer findByCust = customerServices.findByCustIdPage(carecust);
		care.setCustomer(findByCust);//客户
		care.setCareconID(careContacts);//联系人
		care.setCareDate(datenew);;//日期
		care.setCare_userID(carehasman);//执行人
		care.setCareClassity(caretype);//分类
		care.setCarestatue(1283);//状态
		care.setCareContents(textcare);;//内容
		care.setCareFeedback(custreturn);;// 反馈
		care.setRemark(textremark);// 备注
		careServices.addCare(care);
		System.out.println("更新：" + care);
		return "编辑！";
	}
	
	/**
	 * 新增客户关怀
	 * @throws ParseException 
	 */
	@PostMapping("/addCare")
	@ResponseBody
	public String addCare(@RequestParam(name = "caretheme", required = false) String caretheme,
			@RequestParam(name = "custID", required = false) Integer carecust,
			@RequestParam(name = "contID", required = false) Integer careContacts,
			@RequestParam(name = "caredate", required = false) String caredate,
			@RequestParam(name = "doname", required = false) Integer carehasman,
			@RequestParam(name = "textcare", required = false) String textcare,
			@RequestParam(name = "careclassity", required = false) Integer caretype,
			@RequestParam(name = "custreturn", required = false) String custreturn,
			@RequestParam(name = "textremark", required = false) String textremark) throws ParseException {
		// 转换日期格式
		java.sql.Date datenew = java.sql.Date.valueOf(caredate.substring(0, 10));
		System.out.println("时间日期："+datenew);
		Care care = new Care();
		// 修改
		care.setCareTheme(caretheme);//关怀主题
		System.out.println("客户编号："+carecust);
		Customer findByCust = customerServices.findByCustIdPage(carecust);
		care.setCustomer(findByCust);//客户
		care.setCareconID(careContacts);//联系人
		care.setCareDate(datenew);//日期
		care.setCare_userID(carehasman);//执行人
		care.setCareClassity(caretype);//分类
		care.setCarestatue(1283);//状态
		care.setCareContents(textcare);;//内容
		care.setCareFeedback(custreturn);;// 反馈
		care.setRemark(textremark);// 备注
		Care addCare = careServices.addCare(care);
		System.out.println("新增：" + care);
		return "新增！";
	}
	
	
	/**
	 * 导出
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "CareExcelDownloads", method = RequestMethod.GET)
    public void downloadAllClassmate(HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("客户关怀！");
 List<Map<String, String>> selectAll = careServices.selectallInfo();
      
        String fileName = "careinfo"  + ".xls";//设置要导出的文件的名字
        //新增数据行，并且设置单元格数据

        int rowNum = 1;

        String[] headers = { "编号", "关怀主题","客户", "联系人", "日期","关怀类型","所有人","执行人","状态"};
        //headers表示excel表中第一行的表头

        HSSFRow row = sheet.createRow(0);
        //在excel表中添加表头

        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        //在表中存放查询到的数据放入对应的列
        for (Map<String, String> map : selectAll) {
        	HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(String.valueOf(map.get("ID")));
            row1.createCell(1).setCellValue(String.valueOf(map.get("caretheme")));
            row1.createCell(2).setCellValue(String.valueOf(map.get("carecust")));
            row1.createCell(3).setCellValue(map.get("careContacts"));
            row1.createCell(4).setCellValue(map.get("caredate"));
            row1.createCell(5).setCellValue(map.get("caretype"));
            row1.createCell(6).setCellValue(map.get("carehasman"));
            row1.createCell(7).setCellValue(map.get("caredoman"));
            row1.createCell(8).setCellValue(map.get("carestatue"));
            rowNum++;
      		}
              
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }

	
}
